package login.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;

import dao.ManagerMagDao;
import dao.StudentMagDao;
import dao.TeacherMagDao;
import dao.impl.ManagerMagImpl;
import dao.impl.StudentMagImpl;
import dao.impl.TeacherMagImpl;
import domain.Manager;
import domain.Student;
import domain.Teacher;

/**
 * 登陆action
 * 
 * May 9, 2009
 *
 * @author Fabian
 *
 */
public class LoginAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		//获取表单提交的信息
		DynaActionForm daf = (DynaActionForm)form;
		String userName = (String)daf.get("username");
		String password = (String)daf.get("password");
		String role = (String)daf.get("role");
		
		//信息不为空
		if ((userName != null) && (password != null) && (role != null)) {
			//处理学生
			if ("student".equals(role)) {
				StudentMagDao smd = new StudentMagImpl();
				Student stu = smd.getStudent(Integer.parseInt(userName), password);
				if (stu != null) {
					
					HttpSession session = request.getSession(false);
					session.setAttribute("user", stu);
					return mapping.findForward("success");
				} else {
					request.setAttribute("flag", 1);
					return mapping.findForward("fail");
				}
			} else if ("teacher".equals(role)) {	//处理老师
				TeacherMagDao tmd = new TeacherMagImpl();
				Teacher teh = tmd.getTeacher(userName, password);
				if (teh != null) {
					HttpSession session = request.getSession();
					session.setAttribute("user", teh);
					return mapping.findForward("success");
				} else {
					request.setAttribute("flag", 1);
					return mapping.findForward("fail");
				}
			} else if ("manager".equals(role)) {	//处理管理员
				ManagerMagDao mmd = new ManagerMagImpl();
				Manager mr = mmd.getManager(userName, password);
				if (mr != null) {
					HttpSession session = request.getSession();
					session.setAttribute("user", mr);
					return mapping.findForward("success");
				} else {
					request.setAttribute("flag", 1);
					return mapping.findForward("fail");
				}
			}			
		} else {
			return mapping.findForward("fail");
		}		
		
		return mapping.findForward("success");
	}
	
}
